from imports import *
from ui_Reptil import ui_Reptil
from reptil_all_place import reptil_all_place
from reptil_a_place import reptil_a_place
class ui_Main:
    def __init__(self, WIDTH, HEIGHT):
        window = tk.Tk()                                     # 创建窗口, 最后转化成员变量.
        window.title('去哪儿')                               # 设置标题标题
        self.text = '欢迎来到随心旅程!'
        self.WIDTH = WIDTH                                   # 设置窗口宽度
        self.HEIGHT = HEIGHT                                 # 设置窗口高度

        window.geometry(self.getMiddle(window))             # 设置窗口初始位置
        window.resizable(width=False, height=False)         # 设置窗口大小是否可变
        self.window = window                                # 保存窗口为对象的成员变量
        self.initFrame(window)                              # 初始化窗口
        self.loadMain()                                     # 加载主窗口
        self.ui_reptil = ui_Reptil(self.f_reptil)          # 加载UI界面
        self.rep_a_place = reptil_a_place('')
        self.countArea = [0 for _ in range(len(area))]      # 是否出现过
        self.rep_a_place.initImageLink()
        print('Done.')
    def initFrame(self, window):               # 创建所有窗口: 多窗口管理容器( 幸运窗口、爬虫窗口、关于窗口 )

        f_all = ttk.Notebook(window, width = self.WIDTH, height = self.HEIGHT)                        # 创建 Notebook 多窗口管理容器
        self.f_main = tk.Frame(f_all)                       # 创建三个窗口
        self.f_reptil = tk.Frame(f_all)
        self.f_about = tk.Frame(f_all)

        # 加入窗口
        f_all.add(self.f_main, text='信息窗口')
        f_all.add(self.f_reptil, text='爬虫窗口')
        f_all.add(self.f_about, text='关于窗口')

        # 设置主窗口的样式
        f_all.place(x = 0, y = 0)
        # 保存窗口为对象的成员变量
        self.f_all = f_all
    def loadMain(self):                       # 加载主窗口

        self.image1 = self.getImage(filepath=r'images/go.jpg', w=150, h=100)
        self.image2 = self.getImage(filepath=r'images/background1.jpg', w=280, h=150)
        l_img = tk.Label(self.f_main, anchor = 'n', image = self.image1)          # 图片标签 4 默认向上对齐
        l_tell = tk.Label(self.f_main, text = '欢迎来到随心旅程!', font = ('幼圆', 30), image = self.image2, anchor='w', compound='left')              # 提示文本 标签5
        l1 = tk.Label(self.f_main, text="上海", font=('幼圆', 15))  # 地名标签 1
        l2 = tk.Label(self.f_main, text="北京", font=('幼圆', 25))  # 地名标签 2
        l3 = tk.Label(self.f_main, text="杭州", font=('幼圆', 15))  # 地名标签 3



        go = tk.Button(self.f_main, text="Go",                        # go 按钮、 滚动确认键
                          width=400,
                          bd = 0,
                          relief = tk.GROOVE,
                          image = self.image1,
                          font=('幼圆',30),
                          command = self.start                          # 按钮响应 指向 start方法. 按钮被单击时将执行start方法
                          )
        b_chose1 = tk.Button(self.f_main,
                             text = '1',
                             bd = 0,
                             font = ('幼圆', 20),
                             relief = tk.GROOVE,
                             command = lambda :self.chose(self.b_chose1['text']),
                             anchor = 'n',
                             compound = 'top'
                             )
        b_chose2 = tk.Button(self.f_main,
                             text='1',
                             bd=0,
                             font=('幼圆', 20),
                             relief=tk.GROOVE,
                             command=lambda :self.chose(self.b_chose1['text']),
                             anchor='n',
                             compound='top'
                             )
        b_chose3 = tk.Button(self.f_main,
                             text='1',
                             bd=0,
                             font=('幼圆', 20),
                             relief=tk.GROOVE,
                             command=lambda :self.chose(self.b_chose1['text']),
                             anchor='n',
                             compound='top'
                             )
        b_chose4 = tk.Button(self.f_main,
                             text='1',
                             bd = 0,
                             font=('幼圆', 20),
                             relief=tk.GROOVE,
                             command=lambda :self.chose(self.b_chose1['text']),
                             anchor='n',
                             compound='top'
                             )

        go.place(x=200, y=380)                                          # 设置 按钮、标签的初始位置
        b_chose1.place(x=0, y=180)
        b_chose2.place(x=500, y=180)
        b_chose3.place(x=0, y=380)
        b_chose4.place(x=500, y=380)
        l1.place(x=240, y=450)
        l1.place_forget()
        l2.place(x=240, y=490)
        l2.place_forget()
        l3.place(x=240, y=540)
        l3.place_forget()
        l_img.place(x = 20, y = 50)
        l_tell.place(x = 50, y = 30)
        self.l1, self.l2, self.l3, self.l_img, self.l_tell = l1, l2, l3, l_img, l_tell   # 保存为对象成员变量
        self.b_chose1, self.b_chose2, self.b_chose3, self.b_chose4 = b_chose1, b_chose2, b_chose3, b_chose4
        self.go = go
    def open(self):                           # 打开窗口
        self.window.mainloop()

    def getMiddle(self, tk):                                            # 计算窗口处于屏幕中央的坐标(x, y)
        W, H = self.WIDTH, self.HEIGHT
        w = tk.winfo_screenwidth()
        h = tk.winfo_screenheight()
        return '%dx%d+%d+%d' % (W, H, (w - W) / 2, (h - H) / 2)
    def start(self):                           # ok按钮的响应方法，用于实现3个标签切换
        if self.go['text'] == 'Go':
            print('start!')
            self.go['text'] = '测试'
            self.image2 = self.getImage(r'images/background2.jpg',150, 150)
            self.image1 = self.getImage(r'images/next.jpg', 150, 150)
            self.l_tell.configure(text = '接下来请选择您的旅行城市', image = self.image2)
            self.go['image'] = self.image1
        elif self.go['text'] == '测试':
            # 产生四个不同随机且当前未出现的随机数
            orgin = [self.b_chose1['text'], self.b_chose2['text'], self.b_chose3['text'], self.b_chose4['text']]
            # 统计未出现的城市个数，不足4个时 置0
            if self.countArea.count(0) < 4:
                self.countArea = [0 for _ in range(len(area))]
            place = []
            for i in range(4):
                next = random.randint(0, len(area) - 1)
                # 查找没出现过的地区
                while area[next] in orgin or self.countArea[next] == 1:
                    next = random.randint(0, len(area) - 1)
                orgin.append(area[next])
                self.countArea[next] = 1
                place.append(area[next])
            # 获取图片链接
            self.image3 = self.getImageFromUrl(self.rep_a_place.getAImageLink(place[0]), 280, 150)
            self.image4 = self.getImageFromUrl(self.rep_a_place.getAImageLink(place[1]), 280, 150)
            self.image5 = self.getImageFromUrl(self.rep_a_place.getAImageLink(place[2]), 280, 150)
            self.image6 = self.getImageFromUrl(self.rep_a_place.getAImageLink(place[3]), 280, 150)
            # 分别赋值给四个按钮
            self.b_chose1.configure(text=place[0], image=self.image3)
            self.b_chose2.configure(text=place[1], image=self.image4)
            self.b_chose3.configure(text=place[2], image=self.image5)
            self.b_chose4.configure(text=place[3], image=self.image6)
        elif self.go['text'] == '随机推荐':
            self.flag = self.f_main.after(20, self.roll)               # 每隔100毫秒执行 roll 方法、flag保存的是响应id号, 用于停止响应
            self.go['text'] = '停止'                                    # 更改按钮标签，用于判定 响应的停止
        else:                                                           # 当再次点击按钮时，若标签为"停止" 则 进行停止响应操作
            self.f_main.after_cancel(self.flag)                         # 停止对应窗口f_main的after事件，id号为self.flag
            self.go['text'] = '随机推荐'                                 # 还原按钮标签
            msgbox.askyesno("提示窗口", "恭喜您！本次旅程抽到的地点为: " + self.l2['text'] + "\n是否查看相关景区？")   # 弹窗提示

    def chose(self, place):
        print(place)
        # 隐藏4 个 选择按钮
        self.b_chose1.place_forget()
        self.b_chose2.place_forget()
        self.b_chose3.place_forget()
        self.b_chose4.place_forget()
        # 隐藏提示文本的图片
        self.rep_all_place = reptil_all_place('https://you.ctrip.com/sight/' + placesId[indexId[place]] + '/s0-p0.html')
        self.l_tell['image'] = ''
        self.l_tell['text'] = '欢迎到 【' + place + '】 旅行\n' +'该地区共有景区' + str(self.rep_all_place.getNum()) + "家"
        print(self.rep_all_place.url)
        # 弹出景区
        self.l_img.place(x = 20, y = 50)
        self.l_img.configure(image = self.image1)



    def roll(self):                             # 实现滚动标签 3个地名标签标题不断切换、实现向上滚动的视觉效果
                                                                         # 切换策略: 标签标题l2 、 l3 移动到 l1、l2、而l3 随机挑选
        self.l1['text'] = self.l2['text']                                # l2 -> l1
        self.l2['text'] = self.l3['text']                                # l3 -> l2
        next = self.l2['text']                                           # l3 -> next 接下来查找不等于 l1、l2的随机地区名
        while next == self.l1['text'] or next == self.l2['text']:        # 若和l1、l2相等则不断查找
            next = area[random.randint(0, len(area) - 1)]                # 产生[0 - 地区个数 - 1] 之间的随机数 作为 next 即 l3 标签的标题
        self.l3['text'] = next                                           # 查找完毕，next -> l3
        self.setImage(url = self.rep_a_place.getAImageLink(self.l2['text']), x = 400, y = 300)  # 更新图片
        self.flag = self.f_main.after(20, self.roll)                    # 延时50ms递归after继续执行roll方法、并修改flag标记，方便停止操作
    def loadReptil(self):
        f_reptil_image = tk.Label(self.f_repital)
    def getImageFromUrl(self, url, width = 0, height = 0):
        try:
            image_bytes = urlopen(url).read()                   # 1. 获取 图片的二进制数据
            data_stream = io.BytesIO(image_bytes)               # 2. # 创建图片对于的IO流对象
            pil_image = Image.open(data_stream).resize((width, height), Image.ANTIALIAS)  # 3. 根据IO流对象打开图片地址并拉伸图片大小为(width, height)
            return ImageTk.PhotoImage(pil_image)
        except:
            return None
    def setImage(self, url, x=0, y=0):  # 设置标签图片
        try:
            image_bytes = urlopen(url).read()  # 1. 获取 图片的二进制数据
            data_stream = io.BytesIO(image_bytes)  # 2. # 创建图片对于的IO流对象
            pil_image = Image.open(data_stream).resize((x, y), Image.ANTIALIAS)  # 3. 根据IO流对象打开图片地址并拉伸图片大小为x，y
            self.tk_image = ImageTk.PhotoImage(pil_image)  # 4. 保存图片信息到Tk组件
            self.l_img.configure(width=self.WIDTH, height=self.HEIGHT, image=self.tk_image)  # 5. 设置组件信息, 会自动刷新
            return True  # 操作成功返回True
        except:
            return False  # 若 try失败，则说明url有误，返回False
    def getImage(self,filepath,  w = 0, h = 0): # 设置图片大小
        try:
            img = Image.open(filepath).resize((w, h), Image.ANTIALIAS)
            return ImageTk.PhotoImage(img)  # 4. 保存图片信息到Tk组件
        except:
            return None
